import type { FormInstance } from 'element-plus'
import type { ManholeItemType } from './typings'
import { defineComponent, reactive, ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import {
  ElForm,
  ElRow,
  ElCol,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElDatePicker,
  ElRadioGroup,
  ElRadioButton,
  ElLink,
  ElIcon
} from 'element-plus'
import { Plus, WarningFilled } from '@element-plus/icons-vue'
import { GUTTER, SPAN_STYLE_LG_ONE_SM_DOUBLE } from '~/utils/const'
import BaseUpload from '~/components/ProForm/BaseUpload'
import useVuexGetters from '~/hooks/useVuexGetters'
import styles from '../index.module.scss'
import InputTextarea from '~/components/ProForm/InputTextarea'

export default defineComponent({
  name: 'AssetLampPostBasicInformation',
  props: ['detail', 'type'],
  setup: (props: { detail: ManholeItemType; type: string }, { expose }) => {
    const store = useStore()
    const ruleFormRef = ref<FormInstance>()
    const manholeState = useVuexGetters('manhole', ['manholeModelOpt'])
    const assetWorkAreaState = useVuexGetters('assetWorkArea', ['workAreaSelectList'])
    const streetManagementState = useVuexGetters('streetManagement', ['streetSelectList']) // 所属街道
    const optionsValidateForm = reactive<any>(
      Object.assign(
        {
          isDeliver: true, // 投运状态(开关)
          imageUrl: []
        },
        props?.detail?.id // 初始化数据
          ? {
              id: props.detail.id,
              name: props.detail.name, // 设备名称
              code: props.detail.code,
              modelId: props.detail.modelId,
              isDeliver: props.detail.isDeliver,
              deliverDate: props.detail.deliverDate,
              brand: props.detail.brand,
              manufacturer: props.detail.manufacturer,
              workAreaName: props.detail.workAreaName,
              workAreaId: props.detail.workAreaId,
              streetId: props.detail.streetId,
              simNode: props.detail.simNode,
              memo: props.detail.memo,
              imageArr: props.detail?.imageUrl,
              imageUrl: props.detail?.imageUrl
                ? (props.detail?.imageUrl as string)?.split?.(',')
                : []
            }
          : { isDeliver: 1 }
      )
    )
    //  设备型号选择
    const modelChange = (value: string) => {
      manholeState.manholeModelOpt?.value?.forEach((item: any) => {
        if (item.id === value) {
          optionsValidateForm.modelId = item.id
          optionsValidateForm.modelName = item.name
          optionsValidateForm.brand = item.brandName
          optionsValidateForm.manufacturer = item.manufacturer
        }
      })
    }
    // 上传成功回调
    const handleUploadSuccess = (result: Record<string, any>) => {
      const link = result?.data?.link
      if (link) {
        (optionsValidateForm.imageUrl as string[])?.push(link)
      }
    }
    // 移除对应的文件
    const handleRemoveUploadFile = (file: Record<string, any>) => {
      const link = file?.url
      if (link) {
        optionsValidateForm.imageUrl = (optionsValidateForm.imageUrl as string[])?.filter(
          (item) => item !== link
        )
      }
    }
    //  选择工区
    const workAreaChange = (value: string) => {
      assetWorkAreaState.workAreaSelectList?.value?.forEach((item: any) => {
        if (item.name === value) {
          optionsValidateForm.workAreaId = item.id
        }
      })
    }
    onMounted(() => {
      store.dispatch('streetManagement/GetStreetSelectListByUser') // 获取所属街道
    })
    expose({ ruleFormRef, formValues: optionsValidateForm })

    return () => {
      return (
        <ElForm
          ref={ruleFormRef}
          model={optionsValidateForm}
          labelWidth="120px"
          labelPosition="right"
          class={styles['basicInformation-form']}
        >
          <ElRow gutter={GUTTER}>
            <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
              <ElFormItem
                prop="name"
                label="设备名称"
                rules={[
                  {
                    required: true,
                    whitespace: true,
                    message: '请输入设备名称',
                    trigger: 'change'
                  },
                  {
                    min: 3,
                    whitespace: true,
                    message: '请输入3～20字符长度的设备名称',
                    trigger: 'change'
                  }
                ]}
              >
                <ElInput
                  v-model={optionsValidateForm.name}
                  {...{ minlength: 3, maxlength: 20 }}
                  clearable
                  placeholder="请输入设备名称"
                />
              </ElFormItem>
            </ElCol>
            <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
              <ElFormItem
                prop="code"
                label="设备编号"
                rules={[
                  {
                    required: true,
                    whitespace: true,
                    message: '请输入设备编号',
                    trigger: 'change'
                  }
                ]}
              >
                <ElInput
                  v-model={optionsValidateForm.code}
                  {...{ minlength: 3, maxlength: 20 }}
                  clearable
                  placeholder="请输入设备编号"
                />
              </ElFormItem>
            </ElCol>
            <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
              <ElFormItem
                prop="modelId"
                label="设备型号"
                rules={[
                  {
                    required: true,
                    message: '请输入所属区域',
                    trigger: 'change'
                  }
                ]}
              >
                <ElSelect
                  v-model={optionsValidateForm.modelId}
                  filterable
                  clearable
                  placeholder="请输入设备型号"
                  onChange={modelChange}
                >
                  {manholeState.manholeModelOpt?.value?.map((item: any) => (
                    <ElOption key={item?.id} label={item?.name} value={item?.id!} />
                  )) || []}
                </ElSelect>
              </ElFormItem>
            </ElCol>
            <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
              <ElFormItem
                prop="isDeliver"
                label="投运状态"
                rules={[{ required: true, message: '请选择投运状态', trigger: 'change' }]}
              >
                {/* 单选 */}
                <ElRadioGroup
                  class={styles['info-form-item-full-width']}
                  v-model={optionsValidateForm.isDeliver}
                >
                  <ElRadioButton label={1}>已投运</ElRadioButton>
                  <ElRadioButton label={0}>未投运</ElRadioButton>
                </ElRadioGroup>
              </ElFormItem>
            </ElCol>
            <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
              <ElFormItem
                prop="deliverDate"
                label="投运日期"
                rules={[
                  {
                    required: optionsValidateForm.isDeliver,
                    message: '投运状态开时, 投运日期必填',
                    trigger: 'change'
                  }
                ]}
              >
                <ElDatePicker
                  class={styles['info-form-item-full-width']}
                  v-model={optionsValidateForm.deliverDate}
                  valueFormat="YYYY-MM-DD"
                  disabled={!optionsValidateForm.isDeliver}
                  clearable
                  placeholder="请选择"
                />
              </ElFormItem>
            </ElCol>
            <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
              <ElFormItem
                prop="brand"
                label="品牌"
                rules={[
                  {
                    min: 3,
                    whitespace: true,
                    message: '请输入品牌',
                    trigger: 'change'
                  }
                ]}
              >
                <ElInput
                  v-model={optionsValidateForm.brand}
                  {...{ minlength: 3, maxlength: 20 }}
                  clearable
                  placeholder="请输入"
                />
              </ElFormItem>
            </ElCol>
            <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
              <ElFormItem
                prop="manufacturer"
                label="生产厂家"
                rules={[
                  {
                    min: 3,
                    whitespace: true,
                    message: '生产厂家，若输入则应为3～20个字符',
                    trigger: 'change'
                  }
                ]}
              >
                <ElInput
                  v-model={optionsValidateForm.manufacturer}
                  {...{ minlength: 3, maxlength: 20 }}
                  clearable
                  placeholder="请输入"
                />
              </ElFormItem>
            </ElCol>
            <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
              <ElFormItem
                prop="workAreaName"
                label="所属区域"
                rules={[
                  {
                    required: true,
                    message: '请输入所属区域',
                    trigger: 'change'
                  }
                ]}
              >
                <ElSelect
                  v-model={optionsValidateForm.workAreaName}
                  filterable
                  clearable
                  onChange={workAreaChange}
                  placeholder="请输入或选择"
                >
                  {assetWorkAreaState.workAreaSelectList?.value?.map((item: any) => (
                    <ElOption key={item?.id} label={item?.name} value={item?.name!} />
                  )) || []}
                </ElSelect>
              </ElFormItem>
            </ElCol>
            <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
              <ElFormItem prop="streetId" label="所属街道">
                <ElSelect
                  v-model={optionsValidateForm.streetId}
                  filterable
                  clearable
                  placeholder="请输入或选择"
                >
                  {streetManagementState.streetSelectList?.value?.map((item: any) => (
                    <ElOption key={item?.id} label={item?.name} value={item?.id!} />
                  )) || []}
                </ElSelect>
              </ElFormItem>
            </ElCol>
            <ElCol {...SPAN_STYLE_LG_ONE_SM_DOUBLE}>
              <ElFormItem
                prop="simNode"
                label="SIM卡号"
                rules={[
                  {
                    required: false,
                    message: '请输入SIM卡号',
                    trigger: 'change'
                  }
                ]}
              >
                <ElInput
                  v-model={optionsValidateForm.simNode}
                  {...{ minlength: 3, maxlength: 20 }}
                  clearable
                  placeholder="请输入SIM卡号"
                />
              </ElFormItem>
            </ElCol>
            <ElCol>
              <ElFormItem prop="memo" label="备注">
                <InputTextarea
                  v-model:inputTextareaValue={optionsValidateForm.memo}
                  placeholderName="请输入"
                  limitLength={100}
                />
              </ElFormItem>
            </ElCol>
            <ElCol>
              <ElFormItem label="图片" prop="imageUrl">
                <BaseUpload
                  listType="picture-card"
                  fileList={(optionsValidateForm.imageUrl as string[])?.map?.((item) => ({
                    name: '图片',
                    url: item,
                    response: {
                      data: {
                        link: item
                      }
                    }
                  }))}
                  accept=".jpg,.png"
                  limit={12}
                  onSuccess={handleUploadSuccess}
                  onRemove={handleRemoveUploadFile}
                  v-slots={{
                    tip: () => (
                      <section>
                        <ElLink type="info" underline={false} icon={<WarningFilled />}>
                          &nbsp;支持最多上传12张图片
                        </ElLink>
                      </section>
                    )
                  }}
                >
                  <ElIcon>
                    <Plus />
                  </ElIcon>
                  点击上传
                </BaseUpload>
              </ElFormItem>
            </ElCol>
          </ElRow>
        </ElForm>
      )
    }
  }
})
